package controller.admin;

import com.jfoenix.controls.JFXComboBox;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import sql.JDBC_T;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.MessageFormat;
import java.sql.SQLException;

public class AdminSelectCourseStuController {
    @FXML
    private TextField adm_chzforstu_texfld_sid;
    @FXML
    private JFXComboBox adm_chzforstu_combox_cid;

    public void initialize() throws SQLException {
        JDBC_T jdbc_t = new JDBC_T();
        if(jdbc_t.is_conn()){
            ObservableList<String>courseid;
            courseid = FXCollections.observableArrayList();
            String sql = "select CID from course order by CID";
            PreparedStatement preparedStatement = jdbc_t.getConn().prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery(sql);
            while (resultSet.next()) {
                courseid.add(resultSet.getString("CID"));
            }
            resultSet.close();
            preparedStatement.close();
            adm_chzforstu_combox_cid.setItems(courseid);
        }
    }


    public void selectCourseforStu(){
        Alert alert = new Alert(Alert.AlertType.WARNING);
        String sid,cid;
        sid = adm_chzforstu_texfld_sid.getText();
        try{
            cid = (String) adm_chzforstu_combox_cid.getValue();
            if(cid.equals(""));
        }catch (NullPointerException e){
            alert.setContentText("请选择好课程号！");
            alert.showAndWait();
            return;
        }

       String sql = MessageFormat.format("Insert into cscore values ({0}{1}{0},{0}{2}{0});","'",sid,cid);
        JDBC_T jdbc_t = new JDBC_T();
        if(jdbc_t.is_conn()){
            try{
                PreparedStatement preparedStatement = jdbc_t.getConn().prepareStatement(sql);
                System.out.println(sql);
                preparedStatement.execute(sql);
                alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setContentText("选课成功!!!");
                alert.showAndWait();
            }catch (SQLException sqlException){
                alert = new Alert(Alert.AlertType.WARNING);
                alert.setContentText("选课失败!!!请检查后重新输入");
                alert.showAndWait();

            }
        }
    }

}
